<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Configuration;
use app\madmin\model\Configuration as admin;
use app\madmin\model\Merchant;
use think\facade\Cache;
use think\facade\Db;

class ConfigurationService
{

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data): array
    {
        if ($data['type'] === "mallBase") {
            global $user;
            Cache::set(checkRedisKey("MALL_IS_OPEN"), $data['configuration']['is_open']);
            Merchant::update(
                [
                    'name' => $data['configuration']['mall_name'],
                    'logo' => $data['configuration']['logo']
                ],
                [
                    'is_self' => 1,
                    'mall_id' => $user->mall_id
                ]
            );
        }
        if ($data['type'] === "rightsSetting" && $data['configuration']['is_rights_apply'] == 1){
            global $user;
            $order_end_time = Configuration::where('type','tradeSetting')
                ->where('mall_id',$user['mall_id'])
                ->value('configuration');
            $order_end_time = json_decode($order_end_time,true)['order_end_time'];
            $data['configuration']['rights_apply_time'] = $order_end_time;
        }
        $model = admin::create($data);
        return [HTTP_CREATED, $model];
    }

    /**
     * 读取一条数据
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(string $type): array
    {
        $model = admin::find($type);
        if (!empty($model)) {
            $model = admin::find($type)->toArray();
            if ($type == "mallBase") {
                $model['configuration']['cs_is_open'] = $model['configuration']['cs_is_open'] ?? 0; // 是否强制使用官方客服
                $model['configuration']['cs_detail'] = $model['configuration']['cs_detail'] ?? []; // 客服信息
                $model['configuration']['customer_service_type'] = ($model['configuration']['customer_service_type'] == 0) ? 1 : $model['configuration']['customer_service_type'];
            }
            if (isset($model['configuration']) && isset($model['configuration']['logo']) && $model['configuration']['logo'] == "61465115.jpg") {
                $model['configuration']['logo'] = request()->server("REQUEST_SCHEME") . '://' .$_SERVER['HTTP_HOST'].'/'.$model['configuration']['logo'];
            }
        }
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param string $type
     * @param array $data
     * @return array
     */
    public function update(string $type, array $data): array
    {
        if (!isset($data['update_time'])) {
            return $this->save($data);
        }
        $update_time = $data['update_time'];
        unset($data['update_time']);
        if ($type === "rightsSetting" && $data['configuration']['is_rights_apply'] == 1){
            global $user;
            $order_end_time = Configuration::where('type','tradeSetting')
                ->where('mall_id',$user['mall_id'])
                ->value('configuration');
            $order_end_time = json_decode($order_end_time,true)['order_end_time'];
            $data['configuration']['rights_apply_time'] = $order_end_time;
        }
        $model = admin::where('update_time', $update_time)
            ->where('type', $type)
            ->save($data);
        if ($type === "mallBase" && isset($data['configuration']['is_open'])) {
            global $user;
            if($data['configuration']['customer_service_type'] === 1){
                global $user;
                Merchant::where('mall_id',$user['mall_id'])
                    ->update(['customer_service_type' => 1]);
            }
            Cache::set(checkRedisKey("MALL_IS_OPEN"), $data['configuration']['is_open']);
            Merchant::update(
                [
                    'name' => $data['configuration']['mall_name'],
                    'logo' => $data['configuration']['logo']
                ],
                [
                    'is_self' => 1,
                    'mall_id' => $user->mall_id
                ]
            );
        }
        return [HTTP_CREATED, $model];
    }

    /*
     * 自身配置
     */

    public function localRead($type)
    {
        $model = admin::find($type);
        return [HTTP_SUCCESS, $model];
    }

    public function localSave($data)
    {
        global $user;
        $data['create_time'] = date("Y-m-d H:i:s", time());
        $data['mall_id'] = $user['mall_id'];
        $data['configuration'] = json_encode($data['configuration']);
        $model = Db::name("configuration")->insert($data);
        return [HTTP_CREATED, $model];
    }

    public function localUpdate($type, $data)
    {
        global $user;
        $model = admin::find($type);

        if (is_null($model)) {
            $this->localSave($data);
            $model = 1;
        } else {
            $data['configuration'] = json_encode($data['configuration']);
            $data['update_time'] = date("Y-m-d H:i:s", time());
            $model = Db::name("configuration")->where(['type' => $type, 'mall_id' => $user->mall_id])->update($data);
        }

        return [HTTP_CREATED, $model];
    }
}
